//
//  TestViewController.m
//  BlockMemoryTest
//
//  Created by wangrui on 13-11-20.
//  Copyright (c) 2013年 PPS. All rights reserved.
//

#import "TestViewController.h"
#import "TestObject.h"

@interface TestViewController (){
   
}

@property(nonatomic)BOOL boolInstance;

//@property(nonatomic,assign)TestObject* testObj;
@property(nonatomic,retain)TestObject* testObj;
@end

@implementation TestViewController


- (void)dealloc{
    NSLog(@"test view controller dealloc");
    
#if !__has_feature(objc_arc)
    self.testObj = nil;
    
    //NSLog(@"ts when test view controller dealloc:%d",[ts retainCount]);
    
    [super dealloc];
#endif
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)dismiss:(id)sender
{
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)test:(id)sender {
    
    NSString *ts = [NSString stringWithFormat:@"%d",123];
    NSLog(@"ts outblock:%d",[ts retainCount]);//1
    
    TestObject *obj = [[TestObject alloc]init];
    self.testObj = obj;
    
    __block TestViewController *wself = self; //arc 用__weak
    
    [obj testComplete:^{
        NSLog(@"ts inblock before:%d",[ts retainCount]);//2 //当ts为示例变量或全局变量 是retain的是self,不retain ts
                                                            //因为是copy属性,如果是assign熟悉，不做retain操作
        
        NSLog(@"ts inblock after:%d",[ts retainCount]);//2 block里只retain一次外面的对象
        
        NSLog(@"block test:%d",wself.boolInstance);//此时相当引用的self,形成循环强引用,不能释放
    }];
    
    
    NSLog(@"ts after excute block:%d",[ts retainCount]);//仍然为2,说明不是执行完block释放里面的对象,而是block释放时 release
                                                        //因为是copy属性
    

    /**
     * block 为copy属性时,只retain 代码块里的对象。 并且用到self关键字或实例变量都会retain self. 示例变量或全局变量不retain
     * block 传过来的对象参数不retain. block释放时，release一次已经引用的对象
     * 根据上面的规则注意不要引起循环引用的错误
     */
    
    
    
#if !__has_feature(objc_arc)
    [obj release];
#endif
    
}

@end
